<template>
  <div class="product-card-spec-form" curPageName="edit2132131243453">
    <div class="content">
      <!-- 表单内容 -->
      <!-- <span @click="get_postdata(specsArr)">提交的数据</span> -->

      <el-scrollbar>
        <div v-if="specsArr[0].sku_error.length > 0" class="sku__error error_red_box">
          <el-icon style="margin-right: 6px; font-size: 14px; position: relative; top: 2px"><WarningFilled /></el-icon>
          {{ $t("goods_archive.current_system_model_sku") }}

          <span v-for="(tip, index) in specsArr[0].sku_error">
            {{ sku_error_tips[tip] }}<i v-if="!index == specsArr[0].sku_error.length - 1"> , </i>
          </span>
        </div>

        <div class="body" v-loading="edit_page_logding">
          <el-form ref="specRef" :model="specsArr[0].fvalue">
            <el-row :gutter="40">
              <el-col :span="12">
                <el-form-item v-if="props.type == 'edit'" :label="$t('goods_archive.sku_product')">
                  <el-input disabled v-model="specsArr[0].fvalue.sku" class="qf_input sku"></el-input>
                </el-form-item>
                <el-form-item v-else :label="$t('goods_archive.sku_product')" :error="sku_input_error">
                  <el-input
                    @change="check_sku(specsArr[0], specsArr[0].fvalue.sku, index)"
                    @input="specsArr[0].fvalue.sku = specsArr[0].fvalue.sku.replace(/[^a-zA-Z0-9\-\_]/g, '')"
                    v-model="specsArr[0].fvalue.sku"
                    class="qf_input sku"
                  >
                    <template #prefix>{{ sku_before }}-</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col
                v-for="item in specsArr[0].Items"
                :class="props.formConfig.spec_type == 1 ? item.field + ' fooditem' : ''"
                :span="props.formConfig.spec_type == 1 && item.field == 'size' ? 24 : 12"
              >
                <MerakControl
                  v-bind="item"
                  v-model="specsArr[0].fvalue[item.field]"
                  :default-selected-label="specsArr[0].fvalue[`${item.field}_txt`]"
                  :query-options="handleQueryOptions"
                >
                  <!-- 货号体积(m³) -->
                  <template #volume>
                    <el-input
                      class="qf_input"
                      type="text"
                      :disabled="item.disabled"
                      @blur="changeVolume(specsArr[0].fvalue.volume, specsArr[0])"
                      v-num.point
                      v-model="specsArr[0].fvalue.volume"
                    />
                  </template>

                  <!-- 企发颜色 -->
                  <template #qifa_color_id>
                    <el-select
                      :disabled="item.disabled"
                      filterable
                      @change="colorfun(specsArr[0])"
                      value-key="id"
                      class="qf_select"
                      :placeholder="$t('merak.placeholder_select')"
                      v-model="specsArr[0].fvalue.qifa_color_id"
                    >
                      <template v-if="specsArr[0].fvalue.num_in_packing < 2 || url_params.is_suite == 1">
                        <el-option
                          :label="item.label"
                          :value="item.value"
                          v-for="item in item.options.filter(v => v.value != '251')"
                          :key="item"
                        />
                      </template>
                      <!-- 需要多色 -->
                      <template v-else>
                        <el-option :label="item.label" :value="item.value" v-for="item in item.options" :key="item" />
                      </template>
                    </el-select>
                  </template>

                  <!-- 商家颜色 -->
                  <template #supplier_color_id>
                    <el-select
                      :disabled="item.disabled"
                      filterable
                      value-key="id"
                      class="qf_select"
                      :placeholder="$t('merak.placeholder_select')"
                      v-model="specsArr[0].fvalue.supplier_color_id"
                    >
                      <el-option :label="item.label" :value="item.value" v-for="item in item.options" :key="item" />
                    </el-select>
                  </template>

                  <!-- 外包装内数量 -->
                  <template #num_in_packing>
                    <el-input
                      :disabled="url_params.type_id == '14' || item.disabled"
                      @input="change_num_inpaking(specsArr[0], specsArr[0].fvalue.num_in_packing, index)"
                      class="qf_input"
                      type="text"
                      v-number
                      v-model="specsArr[0].fvalue.num_in_packing"
                    />
                  </template>

                  <!-- 无尺码有多色 -->
                  <template #more_color>
                    <div :span="6">
                      <el-popover
                        placement="bottom"
                        width="400"
                        trigger="click"
                        popper-class="own_popper own_popper_big"
                        :visible="specsArr[0].popoverVisible"
                        @show="sizeMiniShow(specsArr[0],specsArr[0].sizeMiniData.dataValue)"
                        @hide="sizeMiniHide(specsArr[0],specsArr[0].sizeMiniData.dataValue)"
                      >
                        <template #reference>
                          <div
                            class="el-input el-input--default qf_input"
                            @click="specsArr[0].popoverVisible = !specsArr[0].popoverVisible"
                            v-click-outside="onClickOutside"
                          >
                            <div class="el-input__wrapper">
                              <div class="el-input__inner">
                                {{ specsArr[0].fvalue.more_color }}
                                <el-input type="hidden" v-model="specsArr[0].fvalue.more_color" />
                              </div>
                            </div>
                          </div>
                        </template>
                        <div class="size_table_box">
                          <editTableMini
                            :disabled="item.disabled"
                            v-bind="specsArr[0].sizeMiniData"
                            @plusCol="plusCol(specsArr[0].sizeMiniData.dataValue, 'minisize')"
                            @delOne="index => delOne(index, specsArr[0].sizeMiniData.dataValue, 'minisize', specsArr[0])"
                         
                            
                            >
                            <!-- 尺码插槽 -->
                            <template #size="{ scoped }">
                              <div>--</div>
                            </template>
                            <!-- 颜色插槽 -->
                            <template #color="{ scoped }">
                              <div v-if="specsArr[0].fvalue.qifa_color_id == '251'">
                                <el-select
                                  filterable
                                  :validate-event="false"
                                  value-key="id"
                                  class="qf_select"
                                  :placeholder="$t('merak.placeholder_select')"
                                  v-model="scoped.row.color"
                                  popper-class="own_popper"
                                >
                                  <el-option
                                    :label="item.label"
                                    :value="item.value"
                                    v-for="item in colors.filter(item => item.value != '251')"
                                    :key="item"
                                  />
                                </el-select>
                              </div>

                              <div v-else style="line-height: 24px">
                                <span v-if="specsArr[0].fvalue.qifa_color_id">
                                  {{ colors.filter(v => v.value == specsArr[0].fvalue.qifa_color_id).map(v => v.label)[0] }}
                                </span>
                              </div>
                            </template>

                            <template #num="{ scoped }">
                              <div>
                                <el-input
                                  @change="mini_size_all_change(specsArr[0].sizeMiniData.dataValue, specsArr[0], scoped.row.num)"
                                  v-number
                                  :validate-event="false"
                                  class="editCon"
                                  v-model="scoped.row.num"
                                ></el-input>
                              </div>
                            </template>
                          </editTableMini>
                        </div>
                        <!-- <div  style="display: flex; justify-content: center;margin-top:6px;"> {{$t("goods_archive.now_num_all")}}: {{specsArr[0].mini_size_all_num}}</div> -->

                        <div class="error_tip">{{ specsArr[0].size_tip }}</div>
                        <div style="display: flex; justify-content: center">
                          <el-button type="primary" :disabled="item.disabled" plain @click="savesize(specsArr[0])">
                            {{ $t("goods_archive.size_btn_save") }}</el-button
                          >
                        </div>
                      </el-popover>
                    </div>
                  </template>

                  <template #size>
                    <!-- 规格类型 spec_type 1 文本 -->

                    <div v-if="props.formConfig.spec_type == 1" class="create_size_box">
                      <el-dropdown trigger="click" style="width: 100%">
                        <div class="el-dropdown-link" style="width: 100%">
                          <div class="el-input el-input--default qf_input">
                            <div class="el-input__wrapper">
                              <div class="el-input__inner">{{ specsArr[0].fvalue.size }}</div>
                            </div>
                          </div>
                        </div>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <div style="margin: 20px">
                              <el-input
                                :disabled="item.disabled"
                                class="qf_input"
                                :validate-event="false"
                                v-model="specsArr[0].fvalue.size_cn"
                                @change="mergeSizeFun(specsArr[0].fvalue.size_cn, specsArr[0].fvalue.size_ru, specsArr[0])"
                                style="max-width: 600px"
                              >
                                <template #prepend>{{ $t("goods_archive.spec_cn") }}</template>
                              </el-input>
                            </div>
                            <div  style="margin: 20px">
                              <el-input
                                class="qf_input"
                                :disabled="item.disabled"
                                :validate-event="false"
                                v-model="specsArr[0].fvalue.size_ru"
                                @change="mergeSizeFun(specsArr[0].fvalue.size_cn, specsArr[0].fvalue.size_ru, specsArr[0])"
                                style="max-width: 600px"
                              >
                                <template #prepend>{{ $t("goods_archive.spec_ru") }}</template>
                              </el-input>
                            </div>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                    <!-- 1：规格类型 spec_type 2 枚举 -->
                    <!-- 2：颜色 多色都要出现配码组 -->
                    <!--:3：套装格式 package_type 1 - 单尺码 2 - 多尺码 -->

                    <div v-if="props.formConfig.spec_type == 2">
                      <div
                        v-if="
                          (props.formConfig.package_type == '2' && specsArr[0].fvalue.num_in_packing > 1) ||
                          (specsArr[0].fvalue.qifa_color_id == '251' && specsArr[0].fvalue.num_in_packing > 1)
                        "
                        :span="6"
                      >
                        <el-popover
                          placement="bottom"
                          width="400"
                          trigger="click"
                          popper-class="own_popper own_popper_big"
                          :visible="specsArr[0].popoverVisible"
                          @show="sizeMiniShow(specsArr[0],specsArr[0].sizeMiniData.dataValue)"
                           @hide="sizeMiniHide(specsArr[0],specsArr[0].sizeMiniData.dataValue)"
                        >
                          <template #reference>
                            <div
                              class="el-input el-input--default qf_input"
                              @click="specsArr[0].popoverVisible = !specsArr[0].popoverVisible"
                              v-click-outside="onClickOutside"
                            >
                              <div class="el-input__wrapper">
                                <div class="el-input__inner">
                                  {{ specsArr[0].fvalue.size }}
                                  <el-input type="hidden" v-model="specsArr[0].fvalue.size" />
                                </div>
                              </div>
                            </div>
                          </template>
                          <div class="size_table_box">
                            <editTableMini
                              :disabled="item.disabled"
                              v-bind="specsArr[0].sizeMiniData"
                              @plusCol="plusCol(specsArr[0].sizeMiniData.dataValue, 'minisize')"
                              @delOne="index => delOne(index, specsArr[0].sizeMiniData.dataValue, 'minisize', specsArr[0])"
                            >
                              <!-- 尺码插槽 -->
                              <template #size="{ scoped }">
                                <div>
                                  <!-- props.formConfig.package_type == '1' && scoped.index>0 -->
                                  <!-- disabled 单尺码多色，只能选择一个尺码，其余不可选 -->
                                  <el-select
                                    filterable
                                    :disabled="props.formConfig.package_type == '1' && scoped.index > 0"
                                    :validate-event="false"
                                    value-key="id"
                                    class="qf_select"
                                    :placeholder="$t('merak.placeholder_select')"
                                    v-model="scoped.row.size"
                                    @change="
                                      props.formConfig.package_type == '1'
                                        ? one_size_many_colors_fun(specsArr[0].sizeMiniData.dataValue, scoped.row.size)
                                        : ''
                                    "
                                    popper-class="own_popper"
                                  >
                                    <el-option :label="item.label" :value="item.value" v-for="item in sizeArr" :key="item" />
                                  </el-select>
                                </div>
                              </template>
                              <!-- 颜色插槽 -->
                              <template #color="{ scoped }">
                                <div v-if="specsArr[0].fvalue.qifa_color_id == '251'">
                                  <el-select
                                    filterable
                                    :validate-event="false"
                                    value-key="id"
                                    class="qf_select"
                                    :placeholder="$t('merak.placeholder_select')"
                                    v-model="scoped.row.color"
                                    popper-class="own_popper"
                                  >
                                    <el-option
                                      :label="item.label"
                                      :value="item.value"
                                      v-for="item in colors.filter(item => item.value != '251')"
                                      :key="item"
                                    />
                                  </el-select>
                                </div>

                                <div v-else style="line-height: 24px">
                                  <span v-if="specsArr[0].fvalue.qifa_color_id">
                                    {{ colors.filter(v => v.value == specsArr[0].fvalue.qifa_color_id).map(v => v.label)[0] }}
                                  </span>
                                </div>
                              </template>

                              <template #num="{ scoped }">
                                <div>
                                  <el-input
                                    @change="
                                      mini_size_all_change(specsArr[0].sizeMiniData.dataValue, specsArr[0], scoped.row.num)
                                    "
                                    v-number
                                    :validate-event="false"
                                    class="editCon"
                                    v-model="scoped.row.num"
                                  ></el-input>
                                </div>
                              </template>
                            </editTableMini>
                          </div>
                          <!-- <div  style="display: flex; justify-content: center;margin-top:6px;"> {{$t("goods_archive.now_num_all")}}: {{specsArr[0].mini_size_all_num}}</div> -->

                          <div class="error_tip">{{ specsArr[0].size_tip }}</div>
                          <div style="display: flex; justify-content: center">
                            <el-button :disabled="item.disabled" type="primary" plain @click="savesize(specsArr[0])">
                              {{ $t("goods_archive.size_btn_save") }}</el-button
                            >
                          </div>
                        </el-popover>
                      </div>
                      <div v-else>
                        <el-select
                          :disabled="item.disabled"
                          filterable
                          value-key="id"
                          @change="singleSizeChange(specsArr[0].fvalue.size, specsArr[0])"
                          class="qf_select"
                          :placeholder="$t('merak.placeholder_select')"
                          v-model="specsArr[0].fvalue.size"
                        >
                          <el-option :label="item.label" :value="item.value" v-for="item in sizeArr" :key="item" />
                        </el-select>
                      </div>
                    </div>
                  </template>
                </MerakControl>
              </el-col>
            </el-row>
          </el-form>

          <!-- 带尺码的规格表格 -->
          <div
            class="nooption specTable"
            style="margin-bottom: 15px"
            v-if="specsArr[0].own_group_specTable.length > 0 && specsArr[0].specTable.columnsValue.length > 0"
          >
            <div v-if="props.formConfig.spec_type == 1" style="margin-bottom: 10px; font-size: 14px">商品内包装规格</div>
            <editTableMini
              @plusCol="plusCol(specsArr[0].specTable.dataValue)"
              @delOne="index => delOne(index, specsArr[0].specTable.dataValue)"
              v-bind="specsArr[0].specTable"
              :disabled="specTableDisabed"
              :plus="props.formConfig.spec_type == 1 ? true : false"
              :bgClass="props.formConfig.spec_type == 1 ? '' : 'bgColorTable'"
            >
              <template #size="{ scoped }">
                <div>
                  {{ scoped.row.line_size }}
                </div>
              </template>

              <template #ean_barcode="{ scoped }">
                <div>
                  <el-input
                    v-number
                    :validate-event="false"
                    class="editCon"
                    v-model="specsArr[0].specTable.dataValue[scoped.index].ean_barcode"
                  ></el-input>
                  <span class="errorTip" v-if="scoped.row.ean_barcode_errInfo">{{ scoped.row.ean_barcode_errInfo }}</span>
                </div>
              </template>

              <template #merge_insole_length="{ scoped }">
                <div>
                  <el-input
                    @input="scoped.row.merge_insole_length = scoped.row.merge_insole_length.replace(/[^0-9\.\_]/g, '')"
                    :validate-event="false"
                    class="editCon"
                    v-model="specsArr[0].specTable.dataValue[scoped.index].merge_insole_length"
                  ></el-input>
                  <span class="errorTip" v-if="scoped.row.merge_insole_length_errInfo">{{
                    scoped.row.merge_insole_length_errInfo
                  }}</span>
                </div>
              </template>
            </editTableMini>
          </div>

          <!-- <span @click="get_postdata(specsArr)">提交的数据</span> -->

          <!-- 套件 -->

          <div class="nooption" v-if="specsArr[0].suiteTable.columnsValue.length > 0 && url_params.is_suite == 1">
            <div style="margin-bottom: 10px; font-size: 14px">套件内详细信息</div>

            <editTableMini v-bind="specsArr[0].suiteTable" :plus="false" :disabled="suiteTableDisabed">
              <template
                v-for="suiteName in specsArr[0].suiteTable.columnsValue.filter(v => v.type === 'select').map(v => v.field)"
                #[suiteName]="scope"
              >
                <MerakControl
                  v-model="specsArr[0].suiteTable.dataValue[scope.scoped.index][scope.scoped.field]"
                  :default-selected-label="specsArr[0].suiteTable.dataValue[scope.scoped.index][`${scope.scoped.field}_txt`]"
                  :query-options="handleQueryOptionsOne"
                  v-bind="specsArr[0].suiteTable.columnsValue.find(v => v.field === suiteName)"
                />
              </template>
            </editTableMini>
          </div>

          <!-- 颜色 -->

          <div v-if="props.formConfig.has_color == 0">
            <uploadPic
              :key="`picture_${dateNow}`"
              ref="skuColorRef"
              v-bind="uploadDataOne"
              :propsDisabled="imgDisabled"
              v-model="specsArr[0].fvalue.imgs"
            >
            </uploadPic>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="goods_spec_footer">
      <el-button @click="emits('close')"> {{ $t("merak.cancel") }}</el-button>
      <el-button type="primary" :loading="saveLoading" @click="get_postdata(specsArr)"> {{ $t("merak.save") }}</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Plus, Edit, Delete, EditPen, CaretTop, CaretBottom } from "@element-plus/icons-vue";

import { ref, reactive, onMounted, getCurrentInstance, nextTick, watch, computed, inject } from "vue";
import MerakControl, { MerakControlProps } from "@/components/MerakControl";

import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";

import { ElButton, ElScrollbar, ElForm, ElMessage, ClickOutside as vClickOutside } from "element-plus";
import I18n from "@/languages/index";
import basicTableSum from "@/components/MerakEditTable/components/basicTable/moreEdit.vue";

import { ResultEnum } from "@/enums/httpEnum";
import { OptionType, getOptions, validsku, saveData } from "@/api/modules/goodsArchive/addGoodsArchive";
import { useRouter, useRoute } from "vue-router";
import editTableMini from "@/components/MerakEditTable/components/editTableMini/index.vue";
import uploadPic from "@/components/uploadFileMerak/picUpload.vue";
import { number } from "mathjs";
import { BlockKeys, BlockRefs } from "../index";
const { query } = useRoute();

const $t = I18n.global.t;
const blocks = inject<BlockRefs>("blocks");
// // 获取spu
// blocks[BlockKeys.base]?.getSpu()
// // 获取颜色下拉
// blocks[BlockKeys.base]?.getColor()
// // 获取码制
// blocks[BlockKeys.base]?.getSize()
//blocks[BlockKeys.clear]?.getModel();

const router = useRouter();
const route = useRoute();
const url_params = ref({
  type_id: "",
  product_id: "",
  is_suite: ""
});
const edit_page_logding = ref(false);
const option_type = ref("edit");
const skuColorRef = ref();
const dateNow = ref();
//图片禁止操作
const imgDisabled = ref(false);
// 初始化选项
onMounted(() => {
  console.log(query);
  url_params.value = {
    type_id: query.t_id?.toString() ?? 0,
    product_id: query.p_id?.toString() ?? "6748009",
    is_suite: query.s_id == "1" ? 1 : 0,
    is_copy: 0,
    goods_id: query.g_id?.toString() ?? 0
  };

  console.log(url_params.value);
  console.log(props.specsInitial);
  initFun();
});

// 保存 loading
const saveLoading = ref(false);

export type FormType = "default" | "edit" | "copy";

const props = defineProps<{
  // 当前模式 default: 添加  edit: 编辑  copy: 复制
  type: FormType;
  //单条数据
  row?: Record<string, any>;
  // 表单配置项
  formConfig: Record<string, any>;
  // 表单渲染数据
  specsInitial: Record<string, any>;
  // 表单只读字段集合
  formReadonly: Array<string>;
  // 回显数据
  formValue: Array<Record<string, any>>;
  tableData: Array<Record<string, any>>;
}>();

const emits = defineEmits<{
  close: [saved?: boolean];
}>();

//编辑代码
const specRef = ref();
const sku_input_error = ref();

const inputRefMap = ref({});
const uploadDataOne = reactive({
  path: "/goods-archive/product-edit/upload-thumbnails"
});
const handleSetInputMap = (el: refItem, item: number) => {
  if (el) {
    inputRefMap.value[`imgRef_${item}`] = el;
  }
};

const Items: MerakControlProps[] = ref([]);
const updateContent = (event, row) => {
  row.num = event.target.innerHTML;
  console.log(event.target.innerHTML);
};

const sku_before = ref("");
const specsArr = ref([
  {
    fvalue: {
      sku: "",
      num_in_packing: 1,
      size_ru: "",
      size_cn: "",
      imgs: []
    },
    mini_size_all_num: 1,
    sku_error: [],
    Items: [],
    own_group_specTable: [],
    popoverVisible: false,
    specTable: {
      columnsValue: [],
      dataValue: []
    },
    suiteTable: {
      columnsValue: [],
      dataValue: []
    },
    sizeMiniData: {
      columnsValue: [
        { field: "size", title: $t("goods_archive.size_table_size") },
        { field: "num", title: $t("goods_archive.size_table_num") },
        { field: "color", title: $t("goods_archive.size_table_color") }
      ],
      dataValue: [
        {
          size: "",
          color: "",
          num: 1
        }
      ]
    }
  }
]);
const specsArrOld = ref([]);

specsArrOld.value = JSON.parse(JSON.stringify(specsArr.value));
const colors = ref([]);
const sizeArr = ref([]);
const cur_sizeStandard = ref();

// 修改码质
watch(
  () => props.sizeStandard,
  val => {
    if (props.sizeStandard) {
      console.log(sizeStandardMap.value[cur_sizeStandard]);

      sizeArr.value = sizeStandardMap.value[cur_sizeStandard];
    }
  }
);

const spmColors = ref([]);
const sizeStandardMap = ref([]);
const specTableDisabed = ref(false);
const suiteTableDisabed = ref(false);

// 初始化接口数据
const initFun = () => {
  dateNow.value = Date.now();
  sku_before.value = blocks[BlockKeys.base]?.getSpu();
  specsArr.value[0].Items = props.specsInitial.info;
  specsArr.value[0].own_group_specTable = props.specsInitial.specTable;

  specsArr.value[0].suiteTable.columnsValue = props.specsInitial.suiteTable;
  specsArr.value[0].specTable.columnsValue = props.specsInitial.specTable;

  sizeStandardMap.value = props.specsInitial.sizeStandardMap;
  sizeArr.value = sizeStandardMap.value[cur_sizeStandard.value];

  // 手输入规格的规格子表格单独处理
  if (specsArr.value[0].specTable.columnsValue.length > 0) {
    var linenum = 1;

    for (let index = 0; index < linenum; index++) {
      var _dataValue_obj = {};
      for (let index = 0; index < specsArr.value[0].specTable.columnsValue.length; index++) {
        var cur = specsArr.value[0].specTable.columnsValue[index];
        _dataValue_obj[cur.field] = "";
      }
      if (props.row?.num_in_packing < 2) {
        _dataValue_obj["size"] = props.row.size;
        _dataValue_obj["line_size"] = props.row.size_txt;
      }
      specsArr.value[0].specTable.dataValue.push(_dataValue_obj);
    }
  }
  if (props.formConfig.spec_type == 1 ) {
    specsArr.value[0].own_group_specTable = [];
  }

  // 套件信息
  if (specsArr.value[0].suiteTable.columnsValue.length > 0) {
    var linenum = 0;
    console.log(url_params.value.type_id);
    if (url_params.value.type_id == 3) {
      linenum = 3;
    }
    if (url_params.value.type_id == 9) {
      linenum = 5;
    }

    for (let index = 0; index < linenum; index++) {
      var _dataValue_obj = {};
      for (let index = 0; index < specsArr.value[0].suiteTable.columnsValue.length; index++) {
        var cur = specsArr.value[0].suiteTable.columnsValue[index];
        _dataValue_obj[cur.field] = "";
      }
      specsArr.value[0].suiteTable.dataValue.push(_dataValue_obj);
    }
  }

  var Items2 = JSON.parse(JSON.stringify(specsArr.value[0].Items));
  for (let index = 0; index < Items2.length; index++) {
    const element = Items2[index];
    if (element.field == "num_in_packing") {
      element["required"] = 1;
    }
    if (element.field == "size") {
      element["required"] = 1;
    }
    if (element.field == "qifa_color_id") {
      specsArr.value[0].Items;
      colors.value = element.options;
    }
    if (element.field == "volume" && url_params.value.type_id == "1") {
      element["custom"] = 1;
    }
    if (element.field == "size" && element.options?.length > 0) {
      sizeArr.value = element.options;
    }

    // 海关编码(俄) 海关编码(中)最大10位数字
    if (element.field == "hs_code" || element.field == "hs_code_cn") {
      element["maxlength"] = 10;
    }
  }

  // var isSize=false;

  // Items2.forEach(element => {
  //   if(element.field=='size'){
  //     isSize=true;
  //   }
  // });
  // isSize=false;
  // // 没有尺码，但可以选多色
  // if(!isSize){
  //   var more_color={
  //     field:'more_color',
  //     required: 1,
  //     title: "多色信息",
  //     type: "input",
  //     custom:1
  //   }
  //   Items2.splice(2,1,more_color)
  // }

  // console.log(isSize);
  // console.log(Items2);

  specsArr.value[0].Items = Items2;

  console.log(props.type);
  var allinfo = blocks[BlockKeys.base]?.getValue();
  cur_sizeStandard.value = allinfo.size_standard;
  console.log(cur_sizeStandard.value);
  console.log(sizeStandardMap.value[cur_sizeStandard.value]);

  console.log(sizeStandardMap.value.length);

  if (!(JSON.stringify(sizeStandardMap.value) === "{}") && sizeStandardMap.value.length != 0) {
    console.log("码质");
    sizeArr.value = sizeStandardMap.value[cur_sizeStandard.value];
  }

  console.log(sizeArr.value);

  console.log(cur_sizeStandard.value);

  // 编辑
  if (props.type == "edit" || props.type == "copy") {
    // 单条值动态放进弹框里面
    var product_id_data = JSON.parse(JSON.stringify(props.row));
    console.log("当行数据");
    console.log(product_id_data);

    // 复制，清空sku以及product_id
    if (props.type == "copy") {
      product_id_data.sku = "";
      product_id_data.product_id = "";
      product_id_data.qifa_color_id = "";
      product_id_data.supplier_color_id = "";
    }

    // 编辑操作禁止修改个别字段
    if (props.type == "edit") {
      for (let index = 0; index < specsArr.value[0].Items.length; index++) {
        const element = specsArr.value[0].Items[index];
        if (product_id_data.form_readonly.includes(element.field)) {
          element["disabled"] = true;
        }
      }
      if (product_id_data.form_readonly.includes("images")) {
        imgDisabled.value = true;
      }

      if (product_id_data.form_readonly.includes("specTable")) {
        console.log("specTableDisabed");
        specTableDisabed.value = true;
        console.log(specTableDisabed.value);
      }

      if (product_id_data.form_readonly.includes("suiteTable")) {
        console.log("suiteTableDisabed");
        suiteTableDisabed.value = true;
        console.log(suiteTableDisabed.value);
      }
    }
    console.log(product_id_data);
    specsArr.value[0].fvalue = product_id_data;

    // 手输入规格
    if (props.formConfig.spec_type == 1) {
      specsArr.value[0].fvalue.size = specsArr.value[0].fvalue.size_cn + "-" + specsArr.value[0].fvalue.size_ru;
    }

    // 尺码表

    specsArr.value[0].sizeMiniData.dataValue = product_id_data.colorsArr ?? [];
    if (specsArr.value[0].sizeMiniData.dataValue.length > 0) {
      mini_size_all_change(specsArr.value[0].sizeMiniData.dataValue, specsArr.value[0]);
    }

    // 多色
    if (specsArr.value[0].fvalue.qifa_color_id == "251") {
      // specsArr.value[0].sizeMiniData.columnsValue = [
      // { field: "size", title:$t("goods_archive.size_table_size") },
      // { field: "num",  title:$t("goods_archive.size_table_num") },
      // { field: "color",title:$t("goods_archive.size_table_color")}
      // ];
    } else {
      // specsArr.value[0].sizeMiniData.columnsValue = [
      // { field: "size", title: $t("goods_archive.size_table_size") },
      // { field: "num", title: $t("goods_archive.size_table_num") }
      // ];
    }

    // 规格表specTable
    if (product_id_data.specTable.length > 0 ) {
      specsArr.value[0].specTable.dataValue = product_id_data.specTable;
      specsArr.value[0].own_group_specTable = product_id_data.specTable;
    }


    // 套件规格表specTable
    if (product_id_data.suiteTable.length > 0) {
      specsArr.value[0].suiteTable.dataValue = product_id_data.suiteTable;
    }

    //跟着规格的图片
    specsArr.value[0].fvalue.imgs = product_id_data.images;

    no_size_more_colors(specsArr.value[0], product_id_data, "init");
  }
  if(url_params.value.type_id=='13' && specsArr.value[0].fvalue.num_in_packing<2){
      specsArr.value[0].own_group_specTable =[]
    }
};

// 没有尺码，但可以选多色
const no_size_more_colors = (ever, product_id_data, type) => {
  if (type != "init") {
    ever.fvalue.more_color = "";
  }


  console.log(product_id_data);
  for (let index = 0; index < ever.Items.length; index++) {
    const element = ever.Items[index];
    if (element.field == "more_color") {
      ever.Items.splice(index, 1);
    }
  }
  if (
    props.formConfig.has_size == 0 &&
    props.formConfig.has_color == 1 &&
    specsArr.value[0].fvalue.qifa_color_id == "251" &&
    specsArr.value[0].fvalue.num_in_packing > 1
  ) {
    var more_color = {
      field: "more_color",
      required: 1,
      title: "多色信息",
      type: "input",
      custom: 1
    };
    console.log(ever.Items);
    // console.log(ever.Items=[])
    ever.Items.splice(2, 0, more_color);
  }
};

//合并规格
const mergeSizeFun = (cn, ru, ever) => {
  if (!!cn || !!ru) {
    ever.fvalue.size = cn + "-" + ru;
  } else {
    ever.fvalue.size = "";
  }
};

const one_size_many_colors = ref(0);
// 插槽单尺码修改
const one_size_many_colors_fun = (data, cursize) => {
  console.log("单尺码多色修改");
  data.forEach(key => {
    console.log(key);
    key.size = cursize;
  });
  one_size_many_colors.value = 1;
};

// 修改体积 鞋类商品的体积0.29
const changeVolume = (volume, ever) => {
  console.log(volume);
  if (url_params.value.type_id == "1") {
    volume = parseFloat(volume);
    if (volume > 0.29) {
      ever.fvalue.volume = 0.29;
    }
  }
};

// 新增规格
const addspecs = (type, ever) => {
  var specsArr2 = JSON.parse(JSON.stringify(specsArr.value));
  var _obj = {};
  if (type == "add") {
    _obj = specsArr2[0];
    for (var i in _obj.fvalue) {
      if (i != "sku") {
        _obj.fvalue[i] = "";
      }
    }
  }
  if (type == "copy") {
    _obj = JSON.parse(JSON.stringify(ever));
  }
  //报错清空
  _obj.sku_error = [];
  //图片清空
  _obj.imgs = [];

  //规格表格只保留置空一条
  if (_obj.specTable.dataValue.length > 0) {
    var one_line = _obj.specTable.dataValue[0];
    for (var i in one_line) {
      one_line[i] = "";
    }
    _obj.specTable.dataValue = [one_line];
    console.log(_obj.specTable.dataValue);
  }

  //套件表格只保留置空一条
  if (_obj.suiteTable.dataValue.length > 0) {
    var one_line = _obj.suiteTable.dataValue[0];
    for (var i in one_line) {
      one_line[i] = "";
    }
    _obj.suiteTable.dataValue = [one_line];
  }

  //sku默认加一
  var prev_sku = _obj.fvalue.sku;
  prev_sku = prev_sku.substr(-1);
  prev_sku = Number(prev_sku);
  if (!prev_sku) {
    prev_sku = 0;
  }
  prev_sku = prev_sku + 1;
  _obj.fvalue.sku = _obj.fvalue.sku.slice(0, -1) + prev_sku;
  specsArr.value.push(_obj);
};

// 删除规格
const delspecs = index => {
  specsArr.value.splice(index, 1);
};

// 遍历颜色 修改颜色
const colorArr = ref([]);

const colorfun = ever => {
  console.log(ever);

  no_size_more_colors(ever);

  // 多色
  if (ever.fvalue.qifa_color_id == "251") {
    if (ever.fvalue.num_in_packing > 1) {
      // 手输入规格的规格子表格单独处理
      ever.specTable.dataValue = [];
      if (ever.specTable.columnsValue.length > 0) {
        var linenum = 1;

        for (let index = 0; index < linenum; index++) {
          var _dataValue_obj = {};
          for (let index = 0; index < ever.specTable.columnsValue.length; index++) {
            var cur = ever.specTable.columnsValue[index];
            _dataValue_obj[cur.field] = "";
          }
          ever.specTable.dataValue.push(_dataValue_obj);
        }
      }
      ever.fvalue.size = "";
      ever.sizeMiniData.dataValue = [{ size: "", color: "", num: 1 }];
    }
  } else {
    console.log(props.row)
    if(props.row?.qifa_color_id=='251'){
       ever.fvalue.size = "";
      ever.sizeMiniData.dataValue = [{ size: "", color: "", num: 1 }];
    }
    if(ever.sizeMiniData.dataValue.length>1){
      ever.fvalue.size = "";
      ever.sizeMiniData.dataValue = [{ size: "", color: "", num: 1 }];
    }




  }

  var specsArr2 = JSON.parse(JSON.stringify(specsArr.value));
  console.log(specsArr2);
  var color_arr = [];
  for (let index = 0; index < specsArr2.length; index++) {
    const element = specsArr2[index];

    console.log(element.fvalue.qifa_color_id);
    if (color_arr.includes(element.fvalue.qifa_color_id)) {
    } else {
      if (element.fvalue.qifa_color_id) {
        color_arr.push(element.fvalue.qifa_color_id);
      }
    }
  }
  colorArr.value = color_arr;

  var colorsall = [];
  for (var i in color_arr) {
    var new_color = {};
    new_color["value"] = color_arr[i];

    for (let index = 0; index < colors.value.length; index++) {
      const element = colors.value[index];
      if (element.value == color_arr[i]) {
        new_color["label"] = element.label;
        new_color["color_image"] = element.color_image;
      }
    }

    colorsall.push(new_color);
  }

  // emit("change", colorsall);

  // console.log(colorsall);
};

const popoverRef = ref();
const popoverVisible = ref(false);
const change_popover_key = ref(false);
const change_popover_item = () => {
  change_popover_key.value = true;
  console.log(change_popover_key.value);
};

const options = [
  {
    value: "Option1",
    label: "Option1"
  },
  {
    value: "Option2",
    label: "Option2"
  },
  {
    value: "Option3",
    label: "Option3"
  },
  {
    value: "Option4",
    label: "Option4"
  },
  {
    value: "Option5",
    label: "Option5"
  }
];
const hasParentClass = (element, className) => {
  // 检查元素是否为null或者undefined
  if (!element) return false;

  // 获取父级元素
  var parent = element.parentElement;

  // 如果父级元素存在，则检查它的类名
  while (parent) {
    if (parent.classList.contains(className)) {
      return true; // 找到匹配的类，返回true
    }
    // 继续向上查找父级元素
    parent = parent.parentElement;
  }

  return false; // 没有找到匹配的类，返回false
};

const onClickOutside = (e: any) => {
  var hasParentWithClass = hasParentClass(e.target, "own_popper"); // 检查父级元素是否有'myParentClass'类
  console.log(hasParentWithClass);
  if (hasParentWithClass) {
  } else {
    for (let index = 0; index < specsArr.value.length; index++) {
      const element = specsArr.value[index];
      element.popoverVisible = false;
      element.size_tip = "";
    }
  }
};

const num_input = ref(1);

// 修改外包装内数量
const change_num_inpaking = (ever, num_input, index: number) => {
  // 手输入规格的规格子表格单独处理
  num_input = parseInt(num_input);
  console.log(num_input);
  if (num_input < 1) {
    console.log("小于");
    ever.fvalue.num_in_packing = 1;
  }


  var message = $t("goods_archive.please_select_size");
  if (props.formConfig.spec_type == 2) {
    no_size_more_colors(ever);
    ever.specTable.dataValue = [];
    if (ever.specTable.columnsValue.length > 0) {
      var linenum = 1;

      for (let index = 0; index < linenum; index++) {
        var _dataValue_obj = {};
        for (let index = 0; index < ever.specTable.columnsValue.length; index++) {
          var cur = ever.specTable.columnsValue[index];
          _dataValue_obj[cur.field] = "";
        }
        ever.specTable.dataValue.push(_dataValue_obj);
      }
    }
    if (props.formConfig.package_type == "2" && ever.fvalue.num_in_packing > 1) {
      message = $t("goods_archive.please_input_size");
    }
    ever.Items.filter(item => {
      if (item.field == "size") {
        item["message"] = message;
      }
    });
    console.log(ever);
  }

  // 文本格式且外包装数量小于2，置空
  if (props.formConfig.spec_type == 1 && num_input < 2 || url_params.value.type_id=='13' &&  num_input < 2 ) {
    ever.own_group_specTable = [];
  } else {
    ever.own_group_specTable = ever.specTable.dataValue;
  }

  if (props.formConfig.package_type == "2" && ever.fvalue.size != "") {
    specRef.value?.resetFields(["size"]);
    ever.fvalue.size = "";
  }
  ever.sizeMiniData.dataValue = [{ size: "", color: "", num: 1 }];
  if(ever.fvalue.qifa_color_id=='251' && num_input < 2 ){
    ever.fvalue.qifa_color_id=''
  }
  mini_size_all_change(ever.sizeMiniData.dataValue, ever);
};

// 修改配码表
const size_tip = ref("");
const findsizetext = id => {
  var curtext = "";
  for (let index = 0; index < sizeArr.value.length; index++) {
    const element = sizeArr.value[index];
    if (element.value == id) {
      curtext = element.label;
    }
  }
  return curtext;
};
const findcolortext = id => {
  var curtext = "";
  console.log(colors);
  for (let index = 0; index < colors.value.length; index++) {
    const element = colors.value[index];
    if (element.value == id) {
      curtext = element.label;
    }
  }
  return curtext;
};

// 后台发送接口验证sku/唯一
const check_sku = async (ever, sku, index) => {
  var sku_before_new = "";
  if (!sku_before.value) {
    sku_before_new = "";
    sku = sku;
  } else {
    if (sku == "") {
      sku = sku_before.value;
    } else {
      sku = sku_before.value + "-" + sku;
    }
  }
  var postsku = await validsku(sku).then(({ code, data }) => {
    edit_page_logding.value = false;
    if (code == ResultEnum.SUCCESS) {
      sku_input_error.value = "";
    } else {
      sku_input_error.value = $t("goods_archive.tip_system_sku_is_has");
      ever.evergo = 0;
    }
  });
  return Promise.resolve(postsku);
};

// 处理获取选项事件
const handleQueryOptions = async (field: string) => {
  return new Promise<MerakControlOption[]>(resolve => {
    getOptions(url_params.value.type_id, field, url_params.value.is_suite).then(({ code, data }) => {
      if (code == ResultEnum.SUCCESS) {
        resolve(data);
      }
    });
  });
};

// 处理获取选项事件
const handleQueryOptionsOne = async (field: string) => {
  return new Promise<MerakControlOption[]>(resolve => {
    const suite = 0;
    getOptions(url_params.value.type_id, field, suite).then(({ code, data }) => {
      if (field === "cc_goods_name") {
        console.log("cc_goods_name", suite);
      }
      if (code == ResultEnum.SUCCESS) {
        resolve(data);
      }
    });
  });
};

// 数字排序
const sortNum = (a, b) => {
  return a - b;
};
// 判断是否是数字
const IsNum = s => {
  var num = /^[0-9]+.?[0-9]*$/; //判断正整数 /^[1-9]+[0-9]*]*$/

  if (!num.test(s)) {
    return false;
  }
  return true;
};

const mini_size_all_change = (dataValue, ever, num) => {
  console.log(dataValue);
  var numall = 0;
  for (let index = 0; index < dataValue.length; index++) {
    const element = dataValue[index];
    var cur_num = element.num;
    if (cur_num) {
      cur_num = parseInt(cur_num);
      if (cur_num == 0 || cur_num == "0") {
        element.num = 1;
        cur_num = 1;
      }
    }

    if (cur_num > 0) {
      numall += cur_num;
    }
  }
  console.log(numall);
  ever.mini_size_all_num = numall;

  var numtit = $t("goods_archive.size_table_num") + " (" + numall + ")";
  ever.sizeMiniData.columnsValue[1] = { field: "num", title: numtit };
};

const savesize = ever => {
  console.log(ever);
  var num_in_packing = ever.fvalue.num_in_packing;
  num_in_packing = Number(num_in_packing);
  var dataValue = ever.sizeMiniData.dataValue;

  var numall = 0;
  var size_text = "";
  var num_text = "";
  var size_color_num = [];
  var confrim_size_arr = [];
  ever.size_tip = "";
  for (let index = 0; index < dataValue.length; index++) {
    const element = dataValue[index];
    var cur_num = parseInt(element.num);
    if (cur_num > 0) {
      numall += cur_num;
      console.log(element.size + element.color + "");
      console.log(element);

      if (ever.fvalue.qifa_color_id != "251") {
        element.color = ever.fvalue.qifa_color_id;
        if (element.size == "" || !!element.num == "") {
          ever.size_tip = $t("goods_archive.pleas_complete_the_code_form");
          ever.fvalue.size = "";
          ever.fvalue.more_color = "";
          return false;
        }
      } else {
        if (props.formConfig.has_size == 0) {
          if (!!element.num == "" || !!element.color == "") {
            ever.size_tip = $t("goods_archive.pleas_complete_the_code_form");
            ever.fvalue.size = "";
            ever.fvalue.more_color = "";
            return false;
          }
        } else {
          if (element.size == "" || !!element.num == "" || !!element.color == "") {
            ever.size_tip = $t("goods_archive.pleas_complete_the_code_form");
            ever.fvalue.size = "";
            ever.fvalue.more_color = "";
            return false;
          }
        }
      }

      if (size_color_num.includes("" + element.size + element.color)) {
        ever.size_tip = $t("goods_archive.value_cannot_repeated");
        ever.fvalue.size = "";
        ever.fvalue.more_color = "";
        return false;
      } else {
        size_color_num.push("" + element.size + element.color);
      }
    } else {
      ever.size_tip = $t("goods_archive.pleas_complete_the_code_form");
      ever.fvalue.size = "";
      ever.fvalue.more_color = "";
      return false;
    }
  }

  if (props.formConfig.has_size != 0) {
    const map = new Map();
    let sizeArr = new Array();
    for (var i = 0; i < dataValue.length; i++) {
      if (dataValue[i].size && dataValue[i].num) {
        if (map.has(dataValue[i].size)) {
          var num_temp = map.get(dataValue[i].size);
          num_temp = parseInt(num_temp);
          map.set(dataValue[i].size, num_temp + parseInt(dataValue[i].num));
        } else {
          sizeArr.push(dataValue[i].size);
          map.set(dataValue[i].size, dataValue[i].num);
        }
      }
    }

    console.log(sizeArr);

    console.log(map);
    console.log("-------------------------");

    let sortArr = sizeArr;
    let str2 = "";
    console.log(sortArr);
    for (var i = 0; i < sortArr.length; i++) {
      console.log(sortArr[i] + "---" + map.get(sortArr[i]));

      var confrim_size_arr_obj = {};
      confrim_size_arr_obj["label"] = findsizetext(sortArr[i]);
      confrim_size_arr_obj["value"] = sortArr[i];
      confrim_size_arr.push(confrim_size_arr_obj);
      size_text += findsizetext(sortArr[i]) + "-";
      num_text += map.get(sortArr[i]) + "-";
    }
  } else {
    dataValue.forEach(tr => {
      console.log(tr.color);
      console.log(findcolortext(tr.color));
      size_text += findcolortext(tr.color) + "-";
      num_text += tr.num + "-";
    });
  }

  console.log(dataValue);
  console.log(size_text);
  console.log(size_text);

  if (numall == num_in_packing) {
    ever.size_tip = "";
    var lastsize_text = size_text.slice(0, -1) + "(" + num_text.slice(0, -1) + ")";

    // 全部通过走啦
    console.log(lastsize_text);

    ever.fvalue.size = lastsize_text;
    ever.fvalue.more_color = lastsize_text;
    ever.confrim_size_arr = confrim_size_arr;
    console.log(confrim_size_arr);

    var pushitem = ever.specTable.columnsValue;
    var specTable_dataValue = [];
    console.log(confrim_size_arr);
    if (pushitem.length > 0) {
      for (let index = 0; index < confrim_size_arr.length; index++) {
        var _obj = {};
        const element = confrim_size_arr[index];
        console.log(element);
        _obj["size"] = element.value;
        _obj["line_size"] = element.label;
        for (let index = 0; index < pushitem.length; index++) {
          const line = pushitem[index];
          if (line.field != "size") {
            _obj[line.field] = "";
          }
        }
        console.log(_obj);
        specTable_dataValue.push(_obj);
      }
    }

    console.log(specTable_dataValue);

    ever.specTable = {
      columnsValue: pushitem,
      dataValue: specTable_dataValue
    };

    ever.popoverVisible = false;
    console.log("尺码表格点击完成，切换了小表格数据")
    if_click_save.value=1;







  } else {
    ever.size_tip = $t("goods_archive.num_all_mast_be") + num_in_packing;
    ever.fvalue.size = "";
    ever.fvalue.more_color = "";
  }
};

// 单尺码修改
const singleSizeChange = (sizeid, ever) => {
  // 只有规格子表格有值才操作，把规格子表格的左侧尺码填写上
  if (ever.specTable.columnsValue.length > 0) {
    ever.specTable.dataValue[0].size = sizeid;
    sizeArr.value.filter(function (item) {
      if (item.value == sizeid) {
        ever.specTable.dataValue[0].line_size = item.label;
      }
      return false;
    });
  }
};

// 操作小表格的增加
const plusCol = (data, type) => {
  var _obj = JSON.parse(JSON.stringify(data[0]));
  if (props.formConfig.package_type == "1") {
    one_size_many_colors.value = 1;
  }
  var one_line_size = "";
  if ((type = "minisize" && one_size_many_colors.value == 1)) {
    one_line_size = _obj.size;
  }
  for (var i in _obj) {
    _obj[i] = "";
  }
  if ((type = "minisize" && one_size_many_colors.value == 1)) {
    _obj.size = one_line_size;
  }

  data.push(_obj);
};
// 操作小表格的删除
const delOne = (index, ever, type, everdata) => {
  if (ever.length > 1) {
    ever.splice(index, 1);
    if (type == "minisize") {
      mini_size_all_change(ever, everdata);
    }
  }
};


  const temp_minisize=ref();
  const if_click_save=ref(0);
  // 配码表格显示
  const sizeMiniShow = (ever) => {
    console.log(ever)
    temp_minisize.value=JSON.parse(JSON.stringify(ever.sizeMiniData))
    if_click_save.value=0;
    console.log( temp_minisize.value)

  }
    // 配码表格隐藏
    const sizeMiniHide = (ever) => {
    console.log(ever)
    console.log( if_click_save.value)
    if(if_click_save.value==0){
      console.log("不是点击了完成按钮的收起")
      console.log( temp_minisize.value)
      if(!(JSON.stringify(ever.sizeMiniData)==JSON.stringify(temp_minisize.value))){
        ever.sizeMiniData=temp_minisize.value
        console.log("发生了变化")
      }
    }
  }


const guige1 = ref("");
const guige2 = ref("");

const guige_all = ref("");

// const visiblechange = (type) => {
//   console.log(type)
//   if (type == false) {
//     guige_all.value = guige1.value + '-' + guige2.value
//   }

// }

const sku_error_tips = {
  one: $t("goods_archive.tip_system_sku_is_has"),
  two: $t("goods_archive.tip_system_sku_is_only"),
  three: $t("goods_archive.tip_no_some_color_size"),
  four: $t("goods_archive.tip_color_qifacolor"),
  five: $t("goods_archive.tip_spec_table"),
  seven:'只能存在一条多色',
  eight:'商品外包装规格不能重复'
};
const add_spec_error = (element, index, errorkey) => {
  var index = 0;
  specsArr.value[index].sku_error.push(errorkey);
  element.sku_error.push(errorkey);
  element.evergo = 0;
};
const del_spec_error = (element, index, errorkey) => {
  specsArr.value[index].sku_error = specsArr.value[index].sku_error?.filter(function (item) {
    return item != errorkey;
  });

  element.sku_error = element.sku_error?.filter(function (item) {
    return item != errorkey;
  });
};
const specVerify = async (element, index, cc_model) => {
  element["evergo"] = 1;

  for (var i in sku_error_tips) {
    del_spec_error(element, index, i);
  }
  console.log(element);


    var check_only = [];
   
    if(!props.row?.form_readonly.includes('sku') || props.type == "copy"){
      console.log("需要验证sku")
      const flag = await check_sku(element, element.fvalue.sku, index);
      }
    

    var qifa_color_only = [];
    var size_cn_only=[];
    var size_ru_only=[];
    var supplier_color_only = [];
    var is_has_more_clors=[];
    var clear_id='';
    if(props.type=='edit'){
      clear_id=props.row?.product_id;
    }
    
    props.tableData.forEach(element => {
      
      if(element.product_id!=clear_id){
        console.log(element.product_id,clear_id)
      size_cn_only.push(element.size_cn)
      size_ru_only.push(element.size_ru)
      if(!("size" in element) || element.size==0){
      element.size='';
     }
    
      var only_qifa_info = " " + element.qifa_color_id + element.num_in_packing + element.size;
      qifa_color_only.push(only_qifa_info);
      console.log(element)
      console.log('每条企发'+only_qifa_info)

      var only_supplier_info = " " + element.num_in_packing + element.size + element.supplier_color_id;

      supplier_color_only.push(only_supplier_info);

      is_has_more_clors.push(element.qifa_color_id)
    }
    });

     if(!("size" in element.fvalue) || element.fvalue.size==0){
      element.fvalue.size='';
     }


    var cur_qifa_only_info = " " + element.fvalue.qifa_color_id + element.fvalue.num_in_packing + element.fvalue.size;
    var cur_supplier_only_info = " " + element.fvalue.num_in_packing + element.fvalue.size + element.fvalue.supplier_color_id;

    var clear_str= new RegExp("undefined","g");
    cur_qifa_only_info=cur_qifa_only_info.replace(clear_str,'')
    cur_supplier_only_info=cur_supplier_only_info.replace(clear_str,'')


    console.log('当前企发颜色组'+cur_qifa_only_info);
  console.log('所有颜色组'+qifa_color_only);
  console.log('当前商家颜色组'+cur_supplier_only_info);
  console.log('所有商家组'+supplier_color_only);

if(element.fvalue.qifa_color_id){
  console.log("验证企发颜色")
  if (qifa_color_only.includes(cur_qifa_only_info)) {
      console.log('企发颜色重复'+cur_qifa_only_info)
      add_spec_error(element, index, "three");
    }
}
   
if(element.fvalue.supplier_color_id){
    if (supplier_color_only.includes(cur_supplier_only_info) && !!element.fvalue.supplier_color_id) {
      console.log('商家颜色重复'+cur_supplier_only_info)
      del_spec_error(element, index, "three");
      add_spec_error(element, index, "three");
    }
  }
    console.log(is_has_more_clors)
    if(is_has_more_clors.includes('251') || is_has_more_clors.includes(251) && element.fvalue.qifa_color_id=='251'){
      add_spec_error(element, index, "seven");
    }



   // 手输入规格验证规格中，规格俄不能存在重复
    if (props.formConfig.spec_type == 1) {
    if (size_cn_only.includes( element.fvalue.size_cn)) {
     
      add_spec_error(element, index, "eight");
    }
    if (size_ru_only.includes( element.fvalue.size_ru)) {
      del_spec_error(element, index, "eight");
      add_spec_error(element, index, "eight");
    }
  }

    
   









  

  if (props.formConfig.has_color == 1) {
    if (element.fvalue.qifa_color_id || element.fvalue.supplier_color_id) {
    } else {
      add_spec_error(element, index, "four");
    }
  }




  // 鞋 清关选--款式--鞋垫内长必填

  var cc_model = blocks[BlockKeys.clear]?.getModel();
  if (url_params.value.type_id == "1" && cc_model == "5511") {
    const post_specTable = specsArr.value[index].specTable.dataValue;
    for (let index = 0; index < post_specTable.length; index++) {
      const spec_table_ever = post_specTable[index];

      console.log(!!spec_table_ever.merge_insole_length);
      if (!!spec_table_ever.merge_insole_length) {
        spec_table_ever.merge_insole_length_errInfo = "";
      } else {
        spec_table_ever.merge_insole_length_errInfo = $t("merak.tip_mast_input");
      }
    }
    for (let i = 0; i < post_specTable.length; i++) {
      const spec_table_ever = post_specTable[i];
      if (spec_table_ever.merge_insole_length_errInfo) {
        add_spec_error(element, index, "five");
      }
    }
  }

  // 规格是手动输入或者 鞋类且大于一
  // var yz_merge_insole_length = false; //是否验证鞋垫内长，有值验证，没值不验证
  const post_specTable = specsArr.value[index].specTable.dataValue;

  if (element.fvalue.num_in_packing > 1) {
    // if (url_params.value.type_id == "1") {
    //   post_specTable.forEach((value, key) => {
    //     value.merge_insole_length_errInfo = "";
    //     if (!!value.merge_insole_length) {
    //       yz_merge_insole_length = true;
    //     }
    //   });
    // }

    // 循环遍历中，规格列中当前列只要存在值，当前列就必须都填写
    var need_verify_key = []; //需要验证必填的列字段key的数组
    post_specTable.forEach((value, key) => {
      console.log(value, key);
      for (var i in value) {
        console.log(i);
        if (i.includes("_errInfo")) {
          value[i] = "";
        }
        if (!!value[i] && need_verify_key.includes(i) == false && i != "size" && i != "line_size") {
          need_verify_key.push(i);
        }
      }
    });
    console.log(need_verify_key);
  }

  if (element.fvalue.num_in_packing > 1) {
    var spec_size_cn_arr = [];
    var spec_size_ru_arr = [];
    var spec_num_arr = 0;
    var spec_ean_barcode_arr = [];
    for (let index = 0; index < post_specTable.length; index++) {
      const spec_table_ever = post_specTable[index];

      if (props.formConfig.spec_type == 1) {
        // 商品规格(中文)不能重复
        if (spec_table_ever.size_cn) {
          spec_table_ever.size_cn_errInfo = "";
          if (spec_size_cn_arr.includes(spec_table_ever.size_cn) || spec_table_ever.size_cn == element.fvalue.size_cn) {
            spec_table_ever.size_cn_errInfo = $t("merak.tip_mast_some");
          } else {
            spec_size_cn_arr.push(spec_table_ever.size_cn);
            spec_table_ever.size_cn_errInfo = "";
          }
        } else {
          spec_table_ever.size_cn_errInfo = $t("merak.tip_mast_input");
        }

        // 商品规格(俄文)
        if (spec_table_ever.size_ru) {
          spec_table_ever.size_ru_errInfo = "";
          if (spec_size_ru_arr.includes(spec_table_ever.size_ru) || spec_table_ever.size_cn == element.fvalue.size_ru) {
            spec_table_ever.size_ru_errInfo = $t("merak.tip_mast_some");
          } else {
            spec_size_ru_arr.push(spec_table_ever.size_ru);
            spec_table_ever.size_ru_errInfo = "";
          }
        } else {
          spec_table_ever.size_ru_errInfo = $t("merak.tip_mast_input");
        }

        // 数量
        if (spec_table_ever.num) {
          spec_table_ever.num_errInfo = "";
          console.log(spec_table_ever.num);
          if (spec_table_ever.num == "0" || spec_table_ever.num == 0 || spec_table_ever.num.includes('.')) {
            spec_table_ever.num_errInfo = "必须大于1得正整数";
          } else {
            spec_num_arr += parseInt(spec_table_ever.num);
          }
        } else {
          spec_table_ever.num_errInfo = $t("merak.tip_mast_input");
        }

        // 条形码
        if (spec_table_ever.ean_barcode) {
          spec_table_ever.ean_barcode_errInfo = "";
          var cur_ean_barcode = spec_table_ever.ean_barcode;
          if (cur_ean_barcode.length == 14 || cur_ean_barcode.length == 13) {
            spec_table_ever.ean_barcode_errInfo = "";
          } else {
            spec_table_ever.ean_barcode_errInfo = $t("goods_archive.tip_barcode_length");
          }
        } else {
          spec_table_ever.ean_barcode_errInfo = $t("merak.tip_mast_input");
        }
      }

      // // 商品类型是鞋
      // if (url_params.value.type_id == "1") {
      //   // 验证鞋垫内长
      //   console.log("验证鞋垫内长");
      //   if (spec_table_ever.merge_insole_length) {
      //     spec_table_ever.merge_insole_length_errInfo = "";
      //   } else {
      //     spec_table_ever.merge_insole_length_errInfo = $t("merak.tip_mast_input");
      //   }
      // }

      // 验证带尺码的规格表格，当前列有一项填写，整列都需要填写

      if (need_verify_key.length > 0) {
        need_verify_key.forEach(need_key => {
          console.log(need_key);
          if (!need_key.includes("_errInfo")) {
            if (spec_table_ever[need_key]) {
            } else {
              spec_table_ever[need_key + "_errInfo"] = $t("merak.tip_mast_input");
            }
          }
        });
      }
    }

    if (props.formConfig.spec_type == 1) {
      // 商品数量必须等于外包装内数量
      var len = post_specTable.length;
      var cur_num_in_packing = element.fvalue.num_in_packing;
      if (cur_num_in_packing == spec_num_arr) {
        if (post_specTable[len - 1].num > 0) {
          post_specTable[len - 1].num_errInfo = "";
        }
      } else {
        post_specTable[len - 1].num_errInfo = $t("goods_archive.num_all_mast_be") + cur_num_in_packing;
      }
    }

    console.log(post_specTable);
    for (let i = 0; i < post_specTable.length; i++) {
      var spec_td = 1;
      const spec_table_ever = post_specTable[i];
      for (var key in spec_table_ever) {
        if (key.includes("_errInfo")) {
          if (spec_table_ever[key]) {
            spec_td = 0;
          }
        }
      }

      if (spec_td == 0) {
        add_spec_error(element, index, "five");
        return false;
      }

      // if (
      //   spec_table_ever.merge_insole_length_errInfo ||
      //   spec_table_ever.size_cn_errInfo ||
      //   spec_table_ever.size_ru_errInfo ||
      //   spec_table_ever.ean_barcode_errInfo ||
      //   spec_table_ever.num_errInfo
      // ) {
      //   add_spec_error(element, index, "five");
      //   return false;
      // }
    }
  }
  return Promise.resolve();
};

const clear_noval_line = data => {
  console.log(data);
  if (!data) {
    data = [];
  }
  data = data.filter(item => {
    var all_null = true;
    for (var i in item) {
      if (i == "size" || i == "line_size") {
      } else {
        if (item[i] != "") {
          all_null = false;
        }
      }
    }
    if (all_null == false) {
      return item;
    }
  });
  console.log(data);
  return data;
};

var check_only = [];

var check_sku_only = [];
const get_postdata = async cc_model => {
  var allArr = JSON.parse(JSON.stringify(specsArr.value));
  console.log(allArr);

  var delobjs = ["confrim_size_arr", "own_group_specTable", "popoverVisible", "sizeMiniData"];
  check_only = [];

  check_sku_only = [];

  var letgo = 1;
  for (let index = 0; index < allArr.length; index++) {
    const element = allArr[index];

    await specVerify(element, index, cc_model);

    element["form"] = element.fvalue;

    for (var i in element.fvalue) {
      if (!!element.fvalue[i]) {
        if (i == "specTable" || i == "colorsArr" || i == "suiteTable") {
        } else {
          element[i] = element.fvalue[i];
        }
      }
    }
    delete element.form;

    console.log(element.specTable.dataValue);
    element["specTable"] = element.specTable.dataValue;

    element["colorsArr"] = element.sizeMiniData.dataValue ?? [];

    if (props.formConfig.package_type == "1" && element.num_in_packing > 1 && element.qifa_color_id != "251") {
      element["colorsArr"] = [{ size: element.size, color: "", num: element.num_in_packing }];
    }
    if (props.formConfig.package_type == "0" && element.num_in_packing > 1 && element.qifa_color_id != "251") {
      element["colorsArr"] = [{ size: "", color: element.qifa_color_id, num: element.num_in_packing }];
    }
    element["suiteTable"] = clear_noval_line(element.suiteTable.dataValue ?? []);

    // 当商品类型配置无颜色，图片跟着货号规格走
    if (props.formConfig.has_color == 0) {
      element["imgs"] = skuColorRef.value.getUploadData();
      delete element.images;
    }

    for (var i in delobjs) {
      delete element[delobjs[i]];
    }
  }

  var letgo = 1;
  for (let index = 0; index < allArr.length; index++) {
    const element = allArr[index];
    if (element.evergo == 0) {
      letgo = 0;
    }
  }

  if (letgo == 1) {
    for (let index = 0; index < allArr.length; index++) {
      const element = allArr[index];
      delete element.evergo;
      delete element.sku_error;
      if (element.specTable.length < 1) {
        delete element.specTable;
      }
      if (element.suiteTable.length < 1) {
        delete element.suiteTable;
      }
    }

    console.log("验证");

    if (!specRef.value) return;
    specRef.value.validate(valid => {
      if (valid) {
        gosave_data(allArr);
      } else {
        console.log("error submit!");
        return false;
      }
    });
  } else {
    ElMessage.error($t("goods_archive.tip_spec_ever_table"));
    return Promise.resolve(false);
  }
};

const gosave_data = allArr => {
  console.log(allArr);
  if (props.type == "edit") {
    allArr[0].sku = allArr[0].sku;
  } else {
    if (!!allArr[0].sku) {
      allArr[0].sku = blocks[BlockKeys.base]?.getSpu() + "-" + allArr[0].sku;
    } else {
      allArr[0].sku = blocks[BlockKeys.base]?.getSpu();
    }
  }

  var allArr_last = {};

  allArr[0].Items.forEach((value, key) => {
    var new_obj = {};
    if (!allArr[0][value.field]) {
      allArr[0][value.field] = "";
    }
    allArr_last[value.field] = allArr[0][value.field];
  });
  var pushobj = ["colorsArr", "imgs", "specTable", "suiteTable", "sku", "size_cn", "size_ru"];
  pushobj.forEach((value, key) => {
    if (!allArr[0][value]) {
      allArr[0][value] = "";
    }
    allArr_last[value] = allArr[0][value];
  });

  console.log(allArr_last);
  console.log(props.row);
  if (props.row?.qifa_color_id == "" && allArr_last?.qifa_color_id) {
    console.log("之前没有企发 颜色，补上了企发颜色");
    allArr_last["qifa_color_first"] = 1;
  }

  var baseAll = blocks[BlockKeys.base]?.getValue();
  console.log(baseAll);
  var params = {
    base: {
      type_id: url_params.value.type_id,
      goods_id: url_params.value.goods_id,
      manufacturer_county_id: baseAll.manufacturer_county_id,
      supplier_id: baseAll.supplier_id,
      brand_id: baseAll.brand_id,
      size_standard: baseAll.size_standard
    },
    spec: [allArr_last]
  };
  console.log("提交给后台的最终数据打印");
  console.log(params);
  confirmWarningMsg({
    msg: props.type == "edit" ? "确认编辑商品" : "确认新增商品",
    callback: (status: string) => {
      if (status === "confirm") {
        saveLoading.value = true;
        edit_page_logding.value = true;
        saveData(params).then(({ code, message }) => {
          saveLoading.value = false;
          edit_page_logding.value = false;
          if (code == ResultEnum.SUCCESS) {
            ElMessage.success(props.type == "edit" ? "编辑商品成功" : "新增商品成功");
            emits("close", true);
          } else {
            const msg = typeof message === "string" ? message : Object.values(message)?.[0];
            ElMessage.error(msg);
          }
        });
      }
    }
  });
};

const resetSpectext = () => {
  specsArr.value = JSON.parse(JSON.stringify(specsArrOld.value));
  initFun();
};

// form ref 集合
const refs = reactive<Array<FormInstance>>([]);

// 暴露的方法
defineExpose({
  get_postdata,
  validate: () => {
    console.log("验证");
    // return new Promise<{
    //   ref?: FormInstance;
    //   err?: string;
    //   other?: boolean;
    // }>(resolve => {
    //   Promise.all(
    //     refs.filter(Boolean).map(ref => {
    //       return new Promise<{
    //         ref?: FormInstance;
    //         err?: string;
    //         other?: boolean;
    //       }>(_resolve => {
    //         ref
    //           .validate()
    //           .then(() => {
    //             _resolve({});
    //           })
    //           .catch(error => {
    //             _resolve({ ref, err: Object.keys(error)?.[0], other: true });
    //           });
    //       });
    //     })
    //   ).then(arr => {
    //     resolve(arr.filter(item => !!item.other)?.[0]);
    //   });
    // });
  },

  resetSpec: () => {
    specsArr.value = JSON.parse(JSON.stringify(specsArrOld.value));
    initFun();
    const timer = requestAnimationFrame(() => {
      refs.filter(Boolean).at(0)?.clearValidate();
      cancelAnimationFrame(timer);
    });
  }
});

const modelValue = defineModel<Record<string, any>>({ default: {} });
</script>

<style scoped lang="scss">
.error_red_box {
  background-color: #fff2f3;
  color: var(--el-color-danger);
  line-height: 30px;
  border-radius: 2px;
  margin-left: 0;
  margin-bottom: 10px;
  padding: 0 12px;
}
.product-card-spec-form {
  display: flex;
  flex-direction: column;
  height: 100%;
  & > :first-child {
    flex: 1;
    margin-bottom: var(--merak-padding);
    min-height: 0;
  }
  .handler {
    text-align: right;
  }
  .goods_spec_footer {
    border-top: 1px solid var(--el-border-color-lighter);
    padding: var(--el-drawer-padding-primary);
    padding-bottom: 0;
    margin: 0 -30px;
    text-align: center;
    background-color: #fff;
    z-index: 9;
  }
}
.size_table_box {
  position: relative;

  .size_plus_all {
    position: absolute;
    right: 10px;
    bottom: 15px;
  }

  .size_plus_all.three {
    right: 180px;
  }
}

.errorTip {
  font-size: 11px;
  color: rgb(228, 15, 15);
  text-align: left;
}

.sku__error {
  color: var(--el-color-danger);
  font-size: 12px;
}

.specs_ever {
  border-radius: 4px;
  border: 1px solid var(--default-input-border);
  margin-bottom: 20px;
  overflow: auto;

  .header {
    padding: 10px 20px;
    background-color: #f8f8fa;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .body {
    padding: 20px;
  }

  :deep(.sku .el-input__wrapper) {
    box-shadow: none;
  }

  :deep(.sku .el-input) {
    border: 0;
  }
}

.error_tip {
  color: var(--el-color-danger);
  font-size: 12px;

  height: 30px;
  line-height: 27px;
  text-align: center;
}

:deep(.header .el-icon) {
  color: var(--el-color-primary);
  font-size: 14px;
  position: relative;
  top: 1px;
}
.merak-control .el-input__wrapper .el-input__inner {
  line-height: 30px !important;
}
</style>

<style>
.sku_detail_drawer .product-card-spec-form .el-form-item {
  display: block;
  justify-content: flex-start !important;
}

.el-popper.is-light.own_popper_big {
  padding: 20px;

  background: #fff;
}

.miniEdit .qf_select,
.miniEdit .qf_select.el-select .el-select__wrapper {
  height: 24px;
  border-bottom: 0;
  box-shadow: 0;
  padding: 0;
  min-height: 24px;
}

.miniEdit .qf_input.el-input .el-input__wrapper,
.miniEdit .el-input__inner {
  height: 24px !important;
  border-bottom: 0;
  min-height: 24px;
  box-shadow: 0;
  padding: 0;
}

.miniEdit .merak-control {
  margin-bottom: 0 !important;
}

.miniEdit .merak-control .el-input__wrapper,
.miniEdit .qf_input.el-input {
  border: 0;
}

.miniEdit .el-form-item__label {
  display: none !important;
}

.miniEdit .el-button {
  background-color: #fff;
}
.sku .el-input__prefix-inner {
  position: relative;
  top: -1px;
}
.nooption .editTableMini .miniEdit .minThead > tr > td {
  min-width: 100px;
}
.nooption .editTableMini .miniEdit .minThead > tr > td.opration {
  min-width: 30px;
}
.sizeMini .el-button--default.is-plain:focus,
.el-button--default.is-plain {
  background: #fff !important;
  padding: 3px 25px;
  font-size: 12px;
}
.size_table_box .el-icon.el-input__icon.el-input__validateIcon {
  display: none;
}

.create_size_box .qf_input.el-input .el-input__wrapper .el-input__inner {
  line-height: 30px !important;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.create_size_box .el-input__wrapper {
  width: 100%;
}

/* .nooption .opration.plus{
      display:none;
    }
    .nooption .minBody tr td:nth-child(2){
      background-color: #F3F4F7;
    } */
.el-col.el-col-24.is-guttered.size {
  padding: 0 !important;
}
/* 选择特定类型的所有单数，并排除前三个 */
.el-drawer .el-drawer__body .el-row .el-col.el-col-12.fooditem:nth-of-type(odd):not(:nth-of-type(-n + 2)) {
  padding-left: 20px !important;
  padding-right: 0 !important;
}
.el-drawer .el-drawer__body .el-row .el-col.el-col-12.fooditem:nth-of-type(even):not(:nth-of-type(-n + 2)) {
  padding-left: 0 !important;
  padding-right: 20px !important;
}
.el-message.el-message--error {
  z-index: 999999999 !important;
}
</style>
